class Snake {

    constructor(option) {
        option = option instanceof Object ? option : {};
        this.width = option.width || 20;
        this.height = option.height || 20;
        this.body = [
            { x: 3, y: 2, color: "red" },
            { x: 2, y: 2, color: "blue" },
            { x: 1, y: 2, color: "blue" },
        ]
        this.direction = option.direction || "right";
        //存储 当前渲染的div
        this.elements = [];

    }

    render(map) {

        this.body.forEach((node) => {
            var snakeNode = document.createElement("div");
            snakeNode.style.width = this.width + "px";
            snakeNode.style.height = this.height + "px";
            snakeNode.style.left = node.x * this.width + "px";
            snakeNode.style.top = node.y * this.height + "px";
            snakeNode.style.position = ps;
            snakeNode.style.backgroundColor = node.color;
            map.appendChild(snakeNode);
            this.elements.push(snakeNode);
        });

    }

    run() {
        //蛇身移动 从后往前开始
        for (var i = this.body.length - 1; i > 0; i--) {
            this.body[i].x = this.body[i - 1].x;
            this.body[i].y = this.body[i - 1].y;
        }

        //操作蛇头
        var head = this.body[0];
        switch (this.direction) {
            case "right":
                head.x += 1;
                break;
            case "left":
                head.x -= 1;
                break;
            case "top":
                head.y -= 1;
                break;
            case "bottom":
                head.y += 1;
                break;
        }
        //删除最后一个

    }

    removeNode(map) {
        this.elements.forEach((node) => {
            map.removeChild(node);
        });

        //清空所有
        this.elements = [];
    }

}